'use client'

import { useState, useEffect } from 'react'
import { MoreHorizontal, PlusCircle } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import RouterHook from '@/components/RouterHook'
import Loading from '@/components/Loading'
import common from '@/utils/common'
import { useDispatch, useSelector } from 'react-redux'
import { selectCurProject } from '@/store/project-slice'
import {
  selectReplies,
  selectIsLoading,
  selectPaginationConfig,
  fetchPaginatedData,
  setPaginationConfig,
  setIsLoading,
} from '@/store/reply-slice'
import { Pagination, PaginationContent, PaginationItem } from '@/components/ui/pagination'
import { ChevronLeft, ChevronRight, CircleHelp } from 'lucide-react'
import { cn } from '@/lib/utils'

const StatusBadge = ({ status, responseText }) => {
  const className =
    status === '2'
      ? 'bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20'
      : status === '1'
      ? 'bg-yellow-50 px-2 py-1 text-xs font-medium text-yellow-800 ring-1 ring-inset ring-yellow-600/20'
      : 'bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700 ring-1 ring-inset ring-blue-700/10'
  const text = status === '2' ? 'published' : status === '1' ? 'publish failed' : 'ready to publish'

  return (
    <div className="flex items-center">
      <span className={cn('inline-flex items-center rounded-md', className)}>{text}</span>
      {status === '1' && (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger>
              <CircleHelp className="ml-1 w-3 h-3 text-muted-foreground" />
            </TooltipTrigger>
            <TooltipContent>
              <p>{responseText}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      )}
    </div>
  )
}

export default function Replies() {
  const curProject = useSelector(selectCurProject)
  const replies = useSelector(selectReplies)
  const isLoading = useSelector(selectIsLoading)
  const paginationConfig = useSelector(selectPaginationConfig)
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(setIsLoading(true))
    if (!curProject) {
      return
    }

    dispatch(
      fetchPaginatedData({
        project_id: curProject.id,
        statusType: paginationConfig.statusType,
        current: paginationConfig.currentPage,
        pageSize: paginationConfig.perPage,
      })
    )
  }, [dispatch, paginationConfig, curProject])

  if (isLoading) {
    return <Loading />
  }

  // if (replies.length <= 0) {
  //   return (
  //     <div
  //       className="flex flex-1 items-center justify-center rounded-lg border border-dashed shadow-sm h-[500px] bg-card"
  //       x-chunk="dashboard-02-chunk-1"
  //     >
  //       <div className="flex flex-col items-center gap-1 text-center">
  //         <h3 className="text-2xl font-bold tracking-tight">You have no replies</h3>
  //         <p className="text-sm text-muted-foreground">Try to reply some post/comment in mentions.</p>
  //         <RouterHook path="/mentions">
  //           <Button className="mt-4">Add Reply</Button>
  //         </RouterHook>
  //       </div>
  //     </div>
  //   )
  // } else {
  return (
    <Card x-chunk="dashboard-06-chunk-0">
      <CardHeader>
        <CardTitle>Replies</CardTitle>
        <CardDescription>Your current replies are listed below.</CardDescription>
      </CardHeader>
      <CardContent>
        <Tabs
          defaultValue={paginationConfig.statusType}
          onValueChange={e => {
            dispatch(setPaginationConfig({ ...paginationConfig, currentPage: 1, statusType: e }))
          }}
        >
          <div className="flex items-center py-2">
            <TabsList className="mr-auto">
              <TabsTrigger value="all" className="text-zinc-600 dark:text-zinc-200">
                All
              </TabsTrigger>
              <TabsTrigger value="0" className="text-zinc-600 dark:text-zinc-200">
                Ready to publish
              </TabsTrigger>
              <TabsTrigger value="1" className="text-zinc-600 dark:text-zinc-200">
                Publish failed
              </TabsTrigger>
              <TabsTrigger value="2" className="text-zinc-600 dark:text-zinc-200">
                Published
              </TabsTrigger>
            </TabsList>
          </div>
        </Tabs>
        <Table>
          <TableHeader>
            <TableRow>
              {/* <TableHead>Keyword</TableHead> */}
              <TableHead className="font-medium w-1/3">Reply</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {replies.map(reply => {
              return (
                <TableRow key={reply.id}>
                  {/* <TableCell className="font-medium">{reply.reddit_fragment.keyword}</TableCell> */}
                  <TableCell className="font-medium w-1/3">
                    {reply?.content?.length > 100 ? reply.content?.substring(0, 100) + '...' : reply.content}
                  </TableCell>
                  <TableCell>
                    <StatusBadge status={reply.status} responseText={reply.response_text} />
                  </TableCell>
                  <TableCell>
                    <div className="grid gap-2 grid-center">
                      <a
                        className="flex items-center font-medium text-primary underline underline-offset-4"
                        href={reply.reddit_fragment?.url}
                        target="_blank"
                      >
                        View post
                      </a>
                      {reply.response_url && (
                        <a
                          className="flex items-center font-medium text-primary underline underline-offset-4"
                          href={reply.response_url}
                          target="_blank"
                        >
                          View reply
                        </a>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </CardContent>
      <CardFooter>
        <div className="w-full flex justify-between items-center">
          <div className="text-xs text-muted-foreground whitespace-nowrap">
            Showing{' '}
            <strong>
              {paginationConfig.currentPage * paginationConfig.perPage - paginationConfig.perPage + 1}-
              {paginationConfig.currentPage * paginationConfig.perPage > paginationConfig.total
                ? paginationConfig.total
                : paginationConfig.currentPage * paginationConfig.perPage}
            </strong>{' '}
            of <strong>{paginationConfig.total}</strong> replies
          </div>
          <div>
            <Pagination>
              <PaginationContent>
                <PaginationItem>
                  <Button
                    variant="outline"
                    className="h-8 w-8 p-0"
                    onClick={() => {
                      dispatch(
                        setPaginationConfig({
                          ...paginationConfig,
                          currentPage: paginationConfig.currentPage - 1,
                        })
                      )
                    }}
                    disabled={paginationConfig.currentPage === 1}
                  >
                    <ChevronLeft className="h-4 w-4" />
                  </Button>
                </PaginationItem>
                <PaginationItem>
                  <Button
                    variant="outline"
                    className="h-8 w-8 p-0"
                    onClick={() => {
                      dispatch(
                        setPaginationConfig({
                          ...paginationConfig,
                          currentPage: paginationConfig.currentPage + 1,
                        })
                      )
                    }}
                    disabled={paginationConfig.currentPage === paginationConfig.lastPage}
                  >
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </PaginationItem>
              </PaginationContent>
            </Pagination>
          </div>
        </div>
      </CardFooter>
    </Card>
  )
  // }
}
